<template>
  <div class="tenantMenu_main main_container add_container">
    <div class="main_main">
      <div class="SearchBar_main main_main_search">
        <div v-if="showMaterialName" class="MaterialName">
          <span class="MaterialNameIcon el-icon-warning" />
          <div v-for="item in materialName" :key="item" class="MaterialNameName">
            <span>{{ item }}</span>
          </div>
          <div class="MaterialNameText">物料暂无库存，不可选择！</div>
        </div>
        <div v-else />
        <div class="main_main_search_item">
          <el-input v-model="pageData.searchValue" style="width:200px;margin-right:10px" placeholder="请输入物料名称或工序" clearable @keyup.enter.native="getList" @clear="getList" />
          <el-button style="background:#387bfc;width:30px;" icon="el-icon-search" @click.stop="getList" />
        </div>
      </div>
      <div ref="table_container" class="table_container">
        <el-table
          ref="table"
          :data="tableData"
          stripe
          border
          :height="tableHeight"

          :cell-style="cellStyle"
          @sort-change="(column)=>{sortChange(column, this)}"
          @selection-change="(val)=>{selectionChange(val, this)}"
        >
          <el-table-column type="selection" width="70" align="center" :selectable="tableSelectable" />
          <el-table-column label="物料编码" min-width="100" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.materialCode }}</span>
            </template>
          </el-table-column>
          <el-table-column label="物料名称" min-width="100" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.materialName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="规格型号" min-width="100">
            <template slot-scope="scope">
              <span>{{ scope.row.materialModel }}</span>
            </template>
          </el-table-column>
          <el-table-column label="物料单位" min-width="100">
            <template slot-scope="scope">
              <span>{{ scope.row.materialUnitName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="工序" min-width="100" prop="engineeringProcessName">
            <template slot-scope="scope">
              <span>{{ scope.row.engineeringProcessName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="备注" width="200">
            <template slot-scope="scope">
              <el-input v-model="scope.row.remark" placeholder="请输入" clearable />
            </template>
          </el-table-column>
          <el-table-column label="退料数量" min-width="100" prop="needNumber">
            <template slot-scope="scope">
              <el-input v-model="scope.row.materialReturnNumber" placeholder="请输入" clearable />
              <!-- <span>{{ scope.row. needNumber }}</span> -->
            </template>
          </el-table-column>

          <!-- <el-table-column label="实际领取数量" min-width="100" prop="hasRequisitionNumber">
            <template slot-scope="scope">
              <span>{{ scope.row. hasRequisitionNumber }}</span>
            </template>
          </el-table-column> -->
        </el-table>
      </div>
    </div>
    <!-- <div class="main_bottoms">
      <pagination
        :total="total"
        :page.sync="pageData.pageNum"
        :limit.sync="pageData.pageSize"
        :selected-num="selectionsAll?selectionsAll.length:0"
        @pagination="getList"
      />
    </div> -->
    <div class="main_bottom">
      <div>
        <el-button type="cancel" @click.stop="cancel">取消</el-button>
        <el-button @click.stop="onSubmit">确定</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { detailList } from '@/api/outsourceManage/outsourceReturnMaterial'

export default {
  name: 'Index',
  props: {
    layerid: {},
    selectedRow: {},
    outsourceOrderId: {}
  },
  data() {
    return {
      pageId: '库存明细', // 页面唯一标识
      pageData: {
        pageNum: 1,
        pageSize: 20,
        orderByColumn: 'updateTime',
        isAsc: 'desc',
        searchValue: '',
        status: 1
      },
      oldTableData: [],
      total: 1, // 数据一共有多少条
      mainId: 'handleId', // 表格行ID
      tableHeight: '0', // 表格高度
      tableData: [], // 表格数据
      tableColumns: [], // 表格实际用的字段
      searchColumns: [], // 搜索区实际用的字段
      selections: [], // 表格当前页所选中的行
      selectionsAll: [], // 表格所有页选中的行
      defaultTableColumns: [// 表格常规字段（初始值）
        { prop: 'materialCode', label: '物料编码' },
        { prop: 'materialName', label: '物料名称' },
        { prop: 'materialModel', label: '规格型号' },
        { prop: 'materialTypeName', label: '物料分类' },
        { prop: 'descriptionName', label: '物料属性' },
        { prop: 'weight', label: '重量' },
        { prop: 'texture', label: '材质' },
        { prop: 'brand', label: '品牌' },
        { prop: 'qualityGuaranteePeriod', label: '保质期(天)' },
        { prop: 'materialUnitName', label: '物料单位' },
        { prop: 'stockNum', label: '库存数量' }
      ],
      defaultSearchColumns: [// 搜索区常规字段（初始值）
        { prop: 'code', label: '批号', type: 'input' }
      ],
      materialName: [],
      tableData2: [],
      showMaterialName: false,
      operationData: [ // 右上角的操作按钮
        { label: '新增', perm: '' },
        { label: '批量删除', perm: '' },
        { label: '批量导出', perm: '' },
        { label: '页面配置', perm: '' }
      ]
    }
  },
  mounted() {
    this.oldTableData = this.$deepClone(this.selectedRow)
    this.selectionsAll = this.selectedRow
    this.getList()
  },
  methods: {
    rowClick(row) {
      if (row.stockNum !== '0') {
        this.$refs.table.toggleRowSelection(row)
      }
    },
    cellStyle({ row, column }) {
      if (column.property == 'stockNum') {
        if (row.stockNum == '0') {
          return {
            color: '#E86D7C'
          }
        }
      }
    },
    // tableSelectable(row, index) {
    //   if (row.stockNum == '0') {
    //     return false
    //   } else {
    //     return true
    //   }
    // },
    // changeTaxPrice(e, row, index) {
    //   if (e.indexOf('.') > -1) {
    //     const afterPoint = e.split('.')
    //     if (e !== 0 && afterPoint[1].length > 2) {
    //       this.tableData[index].outStockNum = e.slice(0, e.indexOf('.') + 3)
    //       this.$message.warning('至多可输入两位小数')
    //     } else if (e == 0) {
    //       this.tableData[index].outStockNum = 0
    //     }
    //   } else {
    //     this.tableData[index].outStockNum = e
    //   }
    // },
    search() {
      const arr = JSON.parse(JSON.stringify(this.selectionsAll))
      this.tableDataOne = this.tableData2.filter(item => item.materialCode && item.materialCode.indexOf(this.pageData.searchValue) !== -1 || item.materialName && item.materialName.indexOf(this.pageData.searchValue) !== -1)
      this.tableData = this.tableDataOne
      this.$nextTick(() => {
        this.selectionsAll = arr
        this.setSelectRow(this)
      })
    },
    getList() {
      if (this.tableData.length > 0) {
        this.oldTableData = this.$deepClone(this.tableData)
      }
      detailList({ outsourceOrderId: this.outsourceOrderId, searchValue: this.pageData.searchValue }).then(res => {
        res.data.forEach(item => {
          item.handleId = item.id
          delete item.id
          item.remark = ''
        })
        // const data = this.$deepClone(this.tableData)
        this.tableData = this.selectedRow.length > 0 ? this.mergeById(res.data, this.oldTableData) : res.data

        // this.materialName = []
        // const data2 = this.$deepClone(res.data)
        // if (res.data) {
        //   data2.forEach(item => {
        //     if (item.stockNum == '0') {
        //       if (this.materialName.length < 5) {
        //         this.materialName.push(item.materialName)
        //         const materialName1 = this.materialName.toString()
        //         const materialName2 = []
        //         materialName2.push(materialName1)
        //         this.materialName = materialName2
        //       } else {
        //         const materialNameOne = this.materialName.toString()
        //         const materialNameTwo = []
        //         materialNameTwo.push(materialNameOne)
        //         materialNameTwo.push('等')
        //         this.materialName = materialNameTwo
        //       }
        //       this.showMaterialName = true
        //     }
        //     item.requisitionNumber = item.needNumber - item.hasRequisitionNumber
        //   })
        //   this.tableData = data2
        //   this.tableData2 = this.$deepClone(res.data)
        // }
        this.$nextTick(() => {
          this.tableHeight = this.$refs.table_container.offsetHeight
          this.setSelectRow(this)
        })
      })
    },
    mergeById(arr1, arr2) {
      console.log('oldTableData', this.oldTableData)
      const resultMap = {}
      // 遍历arr1，以handleId作为键，将元素存入resultMap中
      for (const item of arr1) {
        const { handleId } = item
        resultMap[handleId] = { ...item }
      }
      // 遍历arr2，如果handleId存在于resultMap中，则合并元素；否则不处理
      for (const item of arr2) {
        const { handleId } = item
        if (resultMap[handleId]) {
          resultMap[handleId] = { ...resultMap[handleId], ...item }
        }
      }
      return Object.values(resultMap)
    },
    cancel() {
      this.$layer.close(this.layerid)// 关闭弹框
    },
    onSubmit() {
      console.log(this.selectionsAll)
      if (this.selections.filter(item => !item.materialReturnNumber).length > 0) {
        this.$message.warning('退料数量不能为空')
        return
      } else if (this.selections.filter(item => item.materialReturnNumber && !this.SETTINGS.reg_no_zero.test(item.materialReturnNumber)).length > 0) {
        this.$message.warning('退料数量未正确填写')
        return
      }
      this.$parent.showMaterial(this.selections)
      this.$layer.close(this.layerid)// 关闭弹框
    }
  }
}
</script>

<style lang="less" scoped>
.table_container{
/deep/ .el-input__suffix{
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  height: 36px !important;
}
/deep/ .el-input__inner{
  text-align: unset !important;
}
}
.main_bottoms{
  width: 100%;
  height: 50px;
  background-color: white;
  padding: 0px 30px;
  display: flex;justify-content:flex-end;align-items: center;
}
.formItem_header_operate_items{
  height: 30px;
  display: flex;justify-content: center;align-items: center;
  padding: 0px 10px;font-size: 16px;border-radius: 4px;
  color: rgba(56, 123, 252, 1);background-color: rgba(235, 242, 255, 1);
  .item_name{
    font-size: 14px;padding-left: 10px;
  }
}
.formItem_header_operate_items:hover{
  background-color: rgba(235, 242, 255, 0.5);
}
.main_bottom{
  padding-right: 20px !important;
}
.main_search_item{
  padding-right: 20px !important;
}
.main_main_search_item{
  padding-left: 20px !important;
}
.main_main{
  margin: 0 !important;
  padding-top:0 !important ;
}
.MaterialName {
  display: flex;
  color:rgb(244,156,31);
  justify-content: flex-end;
  align-items: center;
  font-size: 16px;
  padding-top: 20px;
  padding-left: 19px;
  .MaterialNameIcon {
    display: flex;
    align-items: center;
    justify-content: center;
    padding-top: 1px    ;
    padding-left: 2px;
    padding-right: 5px;
  }
}
</style>
